package com_.dxy_test_.synchronized_;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * @Description CountDownLatch用法
 * https://blog.51cto.com/u_15127539/4275048
 * @Author dangxianyue
 * @Date 2023/5/19 15:59
 */
public class CountDownLatchTest {

    /**模拟商品id*/
    private static final String SKU_ID = "A001";
    /**模拟商品库存*/
    private static final Map<String, Integer> SKU_INFO = new HashMap<>();

    static {
        // 初始化库存单元A001有10个库存
        SKU_INFO.put(SKU_ID, 10);
    }

    /**抢购商品*/
    private static void buy() {
        Integer skuNum = SKU_INFO.get(SKU_ID);
        if (skuNum > 0) {
            int remainNum = skuNum - 2; // 每人抢2个
            // 模拟业务处理停顿0.1秒
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            SKU_INFO.put(SKU_ID, remainNum);
            System.out.println("用户" + Thread.currentThread().getId() + "抢购成功，剩余商品数量为" + remainNum);
        } else {
            System.out.println("用户" + Thread.currentThread().getId() + "抢购失败！");
        }
    }

    /**抢购商品*/
    private static void buy2() {
        synchronized (SKU_INFO) {
            buy();
        }
    }

    public static void main(String[] args) {
        int threadNum = 20;//线程数
        CountDownLatch cdl = new CountDownLatch(1);
        for (int i = 0; i < threadNum; i++) {
            new Thread(() -> {
                try {
                    cdl.await();
                    // cdl减到0，表示所有“运动员”都准备就绪，开始跑
//                    buy();
                    buy2();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }).start();
        }

        // 所有运动员都准备好了，发令枪响，开跑
        cdl.countDown();
    }
}
